package com.example.myapplication.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.example.myapplication.api.BackendApiClient
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch

/**
 * 推送通知辅助工具类
 * 处理FCM token的获取和注册
 */
object PushNotificationHelper {
    
    private const val TAG = "PushHelper"
    private const val REQUEST_CODE_NOTIFICATION = 1001
    
    private lateinit var apiClient: BackendApiClient
    private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
    
    /**
     * 初始化推送服务
     * 在Application或MainActivity中调用
     */
    fun initialize(context: Context) {
        Log.d(TAG, "🚀 初始化推送服务")
        
        // 初始化API客户端
        apiClient = BackendApiClient(context.applicationContext)
        
        // 请求通知权限 (Android 13+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (context is Activity) {
                requestNotificationPermission(context)
            }
        }
        
        // 获取FCM Token并注册到后端
        FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
            if (!task.isSuccessful) {
                Log.e(TAG, "❌ 获取FCM Token失败", task.exception)
                return@addOnCompleteListener
            }
            
            // 获取Token成功
            val token = task.result
            Log.d(TAG, "📱 FCM Token: $token")
            
            // 注册到后端服务器
            registerTokenToBackend(token)
        }
    }
    
    /**
     * 请求通知权限 (Android 13+)
     */
    private fun requestNotificationPermission(activity: Activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    activity,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                Log.d(TAG, "📢 请求通知权限")
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(Manifest.permission.POST_NOTIFICATIONS),
                    REQUEST_CODE_NOTIFICATION
                )
            } else {
                Log.d(TAG, "✅ 通知权限已授予")
            }
        }
    }
    
    /**
     * 注册Token到后端服务器
     */
    private fun registerTokenToBackend(token: String) {
        scope.launch {
            try {
                Log.d(TAG, "📤 注册Token到后端...")
                val success = apiClient.registerDeviceToken(token)
                
                if (success) {
                    Log.d(TAG, "✅ Token注册成功，可以接收推送了")
                } else {
                    Log.e(TAG, "❌ Token注册失败")
                }
            } catch (e: Exception) {
                Log.e(TAG, "❌ Token注册异常: ${e.message}", e)
            }
        }
    }
    
    /**
     * 手动刷新Token并注册
     */
    fun refreshToken() {
        FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
            if (task.isSuccessful) {
                val token = task.result
                Log.d(TAG, "📱 刷新FCM Token: $token")
                registerTokenToBackend(token)
            }
        }
    }
    
    /**
     * 检查通知权限状态
     */
    fun hasNotificationPermission(context: Context): Boolean {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.POST_NOTIFICATIONS
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            true // Android 13以下默认有权限
        }
    }
}

